package com.gzxw.mogublog.admin.security;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gzxw.mogublog.commons.config.jwt.Audience;
import com.gzxw.mogublog.commons.config.jwt.JwtTokenUtil;
import com.gzxw.mogublog.commons.config.security.LoginUser;
import com.gzxw.mogublog.xo.global.SysConf;
import com.gzxw.mogublog.xo.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        // 获取请求头中的token，并获得登录信息
        // 该过滤器的作用，1.给安全上下文设置内容 2.刷新登录时间
        LoginUser loginUser = tokenService.getLoginUser(httpServletRequest);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (loginUser != null && authentication == null) {
            long expireTime = loginUser.getExpireTime();
            long currentTime = System.currentTimeMillis();
            if (expireTime - currentTime <= 10 * 60 * 1000L) {
                tokenService.refreshToken(loginUser);
            }

            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
